package leetcode.editor.cn;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

//Java：相交链表
public class IntersectionOfTwoLinkedLists {
    public static void main(String[] args) {
        Solution solution = new IntersectionOfTwoLinkedLists().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) {
     * val = x;
     * next = null;
     * }
     * }
     */
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode curA = headA;
            ListNode curB = headB;

            int lenA = 0, lenB = 0;
            while (curA != null) {
                lenA++;
                curA = curA.next;
            }

            while (curB != null) {
                lenB++;
                curB = curB.next;
            }

            curA = headA;
            curB = headB;
            if (lenB > lenA) {
                int temp = lenA;
                lenA = lenB;
                lenB = temp;

                ListNode tempNode = curA;
                curA = curB;
                curB = tempNode;
            }
            int grep = lenA - lenB;

            while (grep-- > 0) {
                curA = curA.next;
            }

            while (curA != null) {
                if (curA == curB) {
                    return curA;
                }
                curA = curA.next;
                curB = curB.next;
            }
            return null;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}